package com.community.backend.interceptor;


import com.community.backend.context.BaseContext;
import com.community.backend.properties.JwtProperties;
import com.community.backend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(">>> 拦截器生效，URI={}, 头={}", request.getRequestURI(), request.getHeader("Authorization"));
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String token = null;
        //1、从请求头中获取令牌
//        String token = request.getHeader(jwtProperties.getAdminTokenName());
        String header = request.getHeader("Authorization");
        log.info("请求头：{}", header);
        if (header != null && !header.trim().isEmpty()) {
            // 去掉"Bearer "前缀，获取真实token（注意空格，Bearer后有一个空格）
            token = header.replace("Bearer ", "").trim();
            log.info("从请求头提取token：{}", token);
        }
        // 2. 若请求头无有效token，从URL参数获取（新增逻辑，无需处理前缀）支付宝沙箱需要
        if (token == null || token.trim().isEmpty()) {
            token = request.getParameter("token");
            log.info("从URL参数提取token：{}", token);
        }

        // 3. 校验token是否存在
        if (token == null || token.trim().isEmpty()) {
            log.warn("JWT 校验失败，URI={}，token=null，异常=IllegalArgumentException", request.getRequestURI());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 返回401未授权
            return false;
        }
        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            String role = claims.get("role", String.class); // 建议登录时把角色也丢进去
            String id;
            switch (role) {
                case "USER":    id = claims.get("userId",String.class);    break;
                case "PROPERTY":id = claims.get("propertyId",String.class);    break;
                case "ADMIN":   id = String.valueOf(claims.get("adminId",   Integer.class));    break;
                case "SECURITY": id = claims.get("securityId", String.class); break;
                default: throw new RuntimeException("未知角色");
            }
            String name = claims.get("name", String.class);
            //为了在添加员工信息时，能获取修改人的id
            BaseContext.setCurrentId(id);
            BaseContext.setCurrentName(name);
            BaseContext.setCurrentRole(role);
            log.info("拦截器中当前员工：{},{},{}", id, name, role);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            log.warn("JWT 校验失败，URI={}，token={}，异常={}", request.getRequestURI(), request.getHeader("Authorization"), ex.getClass().getSimpleName());        //判断当前拦截到的是Controller的方法还是其他资源
            return false;
        }
    }
}
